package com.winteam.dao;

import javax.swing.*;
import java.sql.*;

public class DbConnection {
        //驱动类名
        private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    //连接数据库路劲URL
    private static final String URL ="jdbc:mysql://localhost:3306/hotel?characterEncoding=UTF-8";

    //登录账号
    private static final  String USER="root";
    //登录密码
    private static final  String PASSWORD="root";

    // 静态代码块加载驱动
    static{
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //获取数据库连接
    public static Connection getConnection(){
            try {
               return DriverManager.getConnection(URL,USER,PASSWORD);
            }catch (Exception e){
                e.printStackTrace();
            }
        return null;
    }
    //查询
    public static ResultSet query(String sql) {

        //获取连接
        Connection connection=getConnection();
        PreparedStatement psd;
        try {
            psd = connection.prepareStatement(sql);
            return psd.executeQuery();
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null,"执行语句出错\n"+e.toString());
            e.printStackTrace();
        }
        return null;
    }
    //增、删、改、查
    public static boolean  updataInfo(String sql) {

        //获取连接
        Connection connection=getConnection();

        try {

            PreparedStatement psd=connection.prepareStatement(sql);
            System.out.println(sql);

            return psd.executeUpdate()>=1? true:false;
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null,"执行语句出错\n"+e.toString());
            e.printStackTrace();
        }
        return false;
    }
    //关闭连接
    public  static  void colseAll(ResultSet rs,Statement stmt,Connection  conn) {
        try { if (rs != null){ rs.close(); }
            if (stmt != null) { stmt.cancel(); }
            if (conn != null) { conn.close(); }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
